﻿using System.Xml;

namespace MsBuildAxTasks
{
    public class AutoRunXml
    {
        XmlDocument doc;
        XmlNode axaptaAutoRun;

        #region properties
        public string XpoFile { get; set; }
        public string ImportWithIds { get; set; }
        public string CompileApplication { get; set; }
        public string DefaultDir { get; set; } 
        #endregion

        #region constructor
        public AutoRunXml() : this("")
        {
        }

        public AutoRunXml(string _defaultDir)
        {
            DefaultDir = _defaultDir;
            Init();
        } 
        #endregion

        private void Init()
        {
            doc = new XmlDocument();

            XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
            doc.AppendChild(docNode);

            axaptaAutoRun = doc.CreateElement("AxaptaAutoRun");
            doc.AppendChild(axaptaAutoRun);
        }

        public void CreateXml(string _xmlFile)
        {
            XmlAttribute versionAttribute = doc.CreateAttribute("version");
            versionAttribute.Value = "4.0";
            XmlAttribute logFileAttribute = doc.CreateAttribute("logFile");
            logFileAttribute.Value = DefaultDir + @"\log.xml";

            axaptaAutoRun.Attributes.Append(versionAttribute);
            axaptaAutoRun.Attributes.Append(logFileAttribute);

            doc.Save(_xmlFile);
        }

        public void AddXpoImport()
        {
            XmlNode xpoImport = doc.CreateElement("XpoImport");

            if (!string.IsNullOrEmpty(XpoFile))
            {
                XmlAttribute productAttribute = doc.CreateAttribute("file");
                productAttribute.Value = XpoFile;
                xpoImport.Attributes.Append(productAttribute);

                if (!string.IsNullOrEmpty(ImportWithIds))
                {
                    XmlAttribute importwithIdsAttribute = doc.CreateAttribute("importWithIds");
                    importwithIdsAttribute.Value = ImportWithIds;
                    xpoImport.Attributes.Append(importwithIdsAttribute);
                }

                doc.DocumentElement.AppendChild(xpoImport);
            }
        }

        public void AddCompileApplication()
        {
            XmlNode compileApplication = doc.CreateElement("CompileApplication");

            XmlAttribute productAttribute = doc.CreateAttribute("crossReference");
            productAttribute.Value = "false";
            compileApplication.Attributes.Append(productAttribute);

            doc.DocumentElement.AppendChild(compileApplication);
        }

    }
}
